package com.killer.conf;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EsConfig {

    @Value("${spring.elasticsearch.rest.uris}")
    private String hostlist;

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        //解析hostlist配置信息
        String[] splitList=hostlist.split(",");
        //创建httpHost数组，用于存放es主机和端口的配置信息
        HttpHost[] httpHostArray = new HttpHost[splitList.length];
        for (int i = 0; i < splitList.length; i++) {
            String item = splitList[i];
            //分割ip和端口号
            String[] ipAndPort=item.split(":");
            httpHostArray[i] = new HttpHost(ipAndPort[0], Integer.parseInt(ipAndPort[1]),"http");
        }
        //创建RestHighLevelClient客户端
        return new RestHighLevelClient(RestClient.builder(httpHostArray));
    }

}
